package com.lookme.lmtool.cracker.filter.noise;

import com.lookme.lmtool.cracker.CrackerConstants;
import com.lookme.lmtool.cracker.annotation.FilterAnnotation;
import com.lookme.lmtool.cracker.annotation.ParamAnnotation;
import com.lookme.lmtool.cracker.filter.AbstractFilter;
import com.lookme.lmtool.utils.ImageUtils;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.util.ArrayList;
import java.util.List;

@FilterAnnotation(groupName = CrackerConstants.FILTER_GROUP_NAME_NOISE,name="去除噪点")
public class FilterClearPointNoise extends AbstractFilter {


    @XStreamAsAttribute
    @ParamAnnotation(name = "黑点检测数量", desc = "点周围黑点的数量",inputType = ParamAnnotation.InputType.Spinner)
    int threshold=2;

    @Override
    public BufferedImageOp getFilter() {
        return null;
    }

    @Override
    public BufferedImage filter(BufferedImage src, BufferedImage dest) {
        if (src != null) {
            int width = src.getWidth();
            int height = src.getHeight();

            for (int x = 0; x < width; x++) {
                List<Integer> list = new ArrayList<Integer>();
                for (int y = 0; y < height; y++) {
                    int count = 0;
                    while (y < height - 1 && ImageUtils.isBlack(src.getRGB(x, y))) {
                        count++;
                        y++;
                    }
                    if (count < threshold && count > 0) {
                        for (int i = 0; i <= count; i++) {
                            list.add(y - i);
                        }
                    }
                }
                if (list.size() != 0) {
                    for (int i = 0; i < list.size(); i++) {
                        dest.setRGB(x, list.get(i), Color.white.getRGB());
                    }
                }
            }

            for (int y = 0; y < height; y++) {
                List<Integer> list = new ArrayList<Integer>();
                for (int x = 0; x < width; x++) {
                    int count = 0;
                    while ( x <width - 1 && ImageUtils.isBlack(src.getRGB(x, y))) {
                        count++;
                        x++;
                    }
                    if (count < threshold && count > 0) {
                        for (int i = 0; i <= count; i++) {
                            list.add(x - i);
                        }
                    }
                }
                if (list.size() != 0) {
                    for (int i = 0; i < list.size(); i++) {
                        dest.setRGB(list.get(i),y, Color.white.getRGB());
                    }
                }
            }
        }
        return dest;
    }
}
